#!/bin/bash

# Determine OS release
OSREL=`lsb_release -is 2>/dev/null`

# On initial install, enable joy service
#
if [ "$OSREL" == "CentOS" -o "$OSREL" == "RedHatEnterpriseServer" ]; then
    # Initial RPM installation
    if [ $1 -eq 1 ] ; then
        if [ -f /usr/lib/systemd/system/joy.service ]; then
            systemctl enable joy.service >/dev/null 2>&1 || :
        elif [ -f /etc/init.d/joy -a -f /usr/sbin/chkconfig ]; then
            chkconfig --add joy 2>&1 || :
        fi
    # Upgrade
    else
        if [ -f /usr/lib/systemd/system/joy.service ]; then
            systemctl daemon-reload
            systemctl try-restart joy.service >/dev/null 2>&1 || :
        elif [ -f /etc/init.d/joy -a -f /usr/sbin/chkconfig ]; then
            service joy condrestart >/dev/null 2>&1 || :
        fi
        # Change owner from root.root to joy.joy
        chown -R joy.joy /usr/local/var/joy /usr/local/var/log || :
    fi
elif [ "$OSREL" == "Ubuntu" -o "$OSREL" == "Debian" ]; then
    # Initial deb installation
    if [ -z $2 ]; then
        if [ -f /usr/lib/systemd/system/joy.service ]; then
            systemctl enable joy.service  >/dev/null 2>&1 || :
        elif [ -f /etc/init.d/joy -a -f /usr/sbin/chkconfig ]; then
            chkconfig --add joy >/dev/null 2>&1 || :
        elif [ -x /usr/sbin/update-rc.d ]; then
            update-rc.d joy defaults >/dev/null 2>&1 || :
        fi
        chown joy.joy /usr/local/var/joy /usr/local/var/log || :
    # Upgrade
    else
        if [ -f /usr/lib/systemd/system/joy.service ]; then
            systemctl daemon-reload
            systemctl try-restart joy.service >/dev/null 2>&1 || :
        elif [ -f /etc/init.d/joy ]; then
            service joy condrestart >/dev/null 2>&1 || :
        fi
        # Change owner from root.root to joy.joy
        chown -R joy.joy /usr/local/var/joy /usr/local/var/log || :
    fi
fi

# Generate SSH upload key
if [ ! -f /usr/local/etc/joy/upload-key ]; then
        ssh-keygen -f /usr/local/etc/joy/upload-key -P "" -t rsa -b 2048
fi
